<template>
  <div>
    <searchBox @handleSearch="handleSearch" @handleReset="handleReset">
      <el-form :model="searchFrom.param" label-width="auto" ref="productRef" label-position="left" :inline="true">
        <el-form-item label="商品名" prop="param.name">
          <el-input v-model.trim="searchFrom.param.name"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="param.siteCategoryId">
          <div style="width: 200px">
            <el-tree-select v-model="searchFrom.param.siteCategoryId" :data="siteProductList"
              :props="{ value: 'id', label: 'name', children: 'children' }" value-key="id" placeholder="请选择"
              check-strictly clearable />
          </div>
        </el-form-item>
        <el-form-item label="商品品牌" prop="param.brandIds">
          <el-select v-model="searchFrom.param.brandIds" placeholder="请选择" clearable filterable reserve-keyword multiple
            style="width: 200px">
            <el-option v-for="dict in product_brand" :key="dict.id" :label="dict.commonName"
              :value="dict.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </searchBox>
    <el-space spacer=" " class="mb8">
      <el-button type="primary" @click="router.back()">返回</el-button>
      <el-button type="primary" @click="batchDown(1)">批量上架</el-button>
      <el-dropdown @command="(command) => batchDown(command)">
        <el-button type="primary">批量下架</el-button>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item :command="0">临时下架</el-dropdown-item>
            <el-dropdown-item :command="2">永久下架</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
      <el-button type="primary" @click="changePrice(0)">快速改价</el-button>
      <el-button type="primary" @click="changePrice(1)">批量改价</el-button>
    </el-space>


    <el-table :data="tableData" @selection-change="changeProduct" style="height: calc(100vh - 280px)">
      <el-table-column type="selection" width="50" />
      <el-table-column property="id" label="ID" align="center" width="50" />
      <el-table-column label="商品信息" width="400">
        <template #default="scope">
          <div style="display: flex; gap: 20px;align-items: center;">
            <div style="width: 50px;">
              <image-preview :src="scope.row.newImage" :width="50" :height="50" />
            </div>
            <el-text line-clamp="3">{{ scope.row.name }}</el-text>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="品牌信息">
        <template #default="scope">
          <div style="display: flex; gap: 20px;align-items: center;">
            <div style="width: 50px;">
              <image-preview :src="scope.row.brand?.host" :width="50" :height="50" />
            </div>
            <el-text line-clamp="3">{{ scope.row.brand?.commonName }}</el-text>
          </div>
        </template>
      </el-table-column>
      <el-table-column property="categoryName" label="商品类型" />
      <el-table-column property="price" label="价格" align="center">
        <template #header>
          价格（{{ priceUnit }}）
        </template>
      </el-table-column>
      <el-table-column property="newStatus" label="状态" align="center" />
      <el-table-column label="操作" align="center" width="250" fixed="right">
        <template #default="scope">
          <el-button link type="primary" @click="choseEdit(0, scope.row)" v-if="scope.row.status == 1">临时下架</el-button>
          <el-button link type="primary" @click="choseEdit(2, scope.row)"
            v-if="scope.row.status == 1 || scope.row.status == 0">永久下架</el-button>
          <el-button link type="primary" @click="choseEdit(3, scope.row)">SKU</el-button>
          <el-button link type="primary" @click="choseEdit(1, scope.row)" v-if="scope.row.status == 0">上架</el-button>
          <el-button link type="primary" @click="openSource(scope.row)">货源</el-button>
        </template>
      </el-table-column>
    </el-table>
    <Pagination :total="total" :limit="searchFrom.pageSize" :page="searchFrom.pageNum" @pagination="paginationList">
    </Pagination>
    <BatchPrice :BatchVisible="BatchVisible" @handleBatchClose="handleBatchClose" :websiteId="route.query.id"
      :languageId="route.query.languageId" @handleBatchSure="handleBatchSure"></BatchPrice>
    <FastPrice :websiteId="route.query.id" @handleFastClose="handleBatchClose" :productList="productCheckList"
      :FastVisible="FastVisible"></FastPrice>

    <el-dialog v-model="skuVisible" :title="publicFrom.name" @close="handleBatchClose" width="40%">

      <el-table :data="skuList" style="height: calc(100vh - 640px);margin: 10px 0;">
        <el-table-column width="150">
          <template #default="scope">
            <image-preview :src="scope.row.skuImage" :width="100" :height="80" />
          </template>
        </el-table-column>
        <el-table-column label="商品规格" prop="optionValueNames" />
        <el-table-column prop="crossedPrice" align="center">
          <template #header="scope">
            划线价（{{ priceUnit }}）
          </template>
        </el-table-column>
        <el-table-column prop="sellingPrice" align="center">
          <template #header="scope">
            销售价（{{ priceUnit }}）
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>


    <PublicSource :PublicDialog="PublicDialog" :publicFrom="publicFrom" @handlePublicSure="handlePublicSure"
    @handlePublicClose="handlePublicClose"></PublicSource>
  </div>
</template>
<script setup scoped>
import { ref, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import BatchPrice from "./components/BatchPrice.vue";
import FastPrice from "./components/FastPrice.vue";
import PublicSource from "../product/publicPage/publicSource.vue";

const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const product_brand = ref([]); //商品品牌列表数据
const siteProductList = ref([]); //商品分类
const total = ref(0);
const tableData = ref([]);
const newList = ref([]); //勾选的id
const BatchVisible = ref(false)//批量改价弹窗
const FastVisible = ref(false)//批量改价弹窗
const skuVisible = ref(false)//查看SKU
const PublicDialog = ref(false)//默认货源弹出框是false

const priceUnit = ref('')//货币名称
const skuList = ref([])//货币名称

const publicFrom = ref({})//公共赋值

const productCheckList = ref([]);//勾选的全部信息数据
const searchFrom = ref({
  pageNum: 1,
  pageSize: 10,
  param: {
    websiteProductId: null,
    siteCategoryId: null, //站点商品分类
    name: "", //商品名称
    brandIds: []
  },
}); //搜索参数
onMounted(() => {
  getBasics()
  getLanguage();
  getList();
});
const getList = () => {
// sitewebsiteproductList，原来的站点商品接口，现在改为websiteproductList（全局需要改）
// return
  searchFrom.value.param.websiteProductId = Number(route.query.id);
  product.general
    .websiteproductList({
      data: searchFrom.value,
    })
    .then((res) => {
      newList.value = [];
      total.value = res.total ? res.total : 0;
      if (res.data?.length) {
        res.data = res.data.map(code => {
          return {
            ...code,
            newStatus: code.status === 1 ? '已上架' : code.status === 2 ? '已永久下架' : code.status === 0 ? '已临时下架' : '',
            newImage: handleImage(code)
          }
        })
      }
      tableData.value = res.data;
    });
};


const choseEdit = (index, rowItem) => {// 0是临时2是永久1
  let newProductLists = [];
  if (index == 0) {//临时下架
    newProductLists.push(rowItem.productId)
    processingInstructionFrame(index, newProductLists)

  } else if (index == 1) {//上架
    newProductLists.push(rowItem.productId)
    processingInstructionFrame(index, newProductLists)
  } else if (index == 2) {//永久下架
    newProductLists.push(rowItem.productId)
    processingInstructionFrame(index, newProductLists)
  } else {// 查看SKU
    site.general.sitewebsitemoduleGetproductskulistbyid(
      {
        pathParams: {
          id: rowItem.id
        }
      }
    ).then(res => {
      if (res.code === 200) {
        publicFrom.value = rowItem
        skuVisible.value = true
      }
      skuList.value = res.data;
    });
  }
};
const openSource=(item)=>{
  let from ={
    ...item,
    id: item.productId

  }
  publicFrom.value = item
  PublicDialog.value = true
}
// 批量下架
const batchDown = (e) => {
  console.log(e);
  processingInstructionFrame(e, newList.value);
};
const processingInstructionFrame = (index, list) => {
  if (!list.length) return proxy.$modal.msgWarning("请选择商品");
  let description = index ? '是否确认永久下架商品？' : '是否确认临时下架商品？'
  if (index === 1) {
    proxy.$modal.confirm('是否确认上架商品？').then(() => {
      product.product
        .productCheck({
          data: {
            productIds: list,
            websiteIds: [Number(route.query.id)],
          },
        })
        .then((res) => {
          if (res.data.checkStatus.length) return proxy.$modal.msgWarning("检测结果不通过");
          product.product
            .productPublish({
              data: {
                productIds: list,
                websiteIds: [Number(route.query.id)],
              },
            })
            .then((ProductRes) => {
              if (ProductRes.code !== 200) return;
              getList();
              proxy.$modal.msgSuccess(ProductRes.message);
            });
        })
    })

  } else {
    proxy.$modal.confirm(description).then(() => {
      product.product
        .productTakedown({
          data: {
            productIds: list,
            websiteIds: [Number(route.query.id)],
            takeDownCode: index
          },
        })
        .then((res) => {
          if (res.code !== 200) return;
          getList();
          proxy.$modal.msgSuccess(res.message);
        });
    });
  }
}

// 搜索
const handleSearch = () => {
  getList();
};
// 搜索重置
const handleReset = () => {
  searchFrom.value.param.brandIds = []
  proxy.resetForm("productRef");
  getList();
};
// 分页
const paginationList = (e) => {
  searchFrom.value.pageNum = e.page;
  searchFrom.value.pageSize = e.limit;
  getList();
};
const changeProduct = (selection) => {
  productCheckList.value = selection
  newList.value = selection.map((item) => item.productId);
};
// 获取商品列表
const getLanguage = () => {
  let from = {
    pageNum: 1,
    pageSize: 999,
    param: {
      websiteId: Number(route.query.id),
      languageId: Number(route.query.languageId),
      fatherId: 0,
    },
  };
  site.general
    .sitecategoryList({
      data: from,
    })
    .then((res) => {
      siteProductList.value = res.data;
    });
  // 商品品牌
  site.general
    .sitewebsitebrandList({
      data: {
        pageNum: 1,
        pageSize: 999,
        param: {
          websiteId: Number(route.query.id),
          moduleId: null, //模块id
        },
      },
    })
    .then((response) => {
      product_brand.value = response.data;
    });
};
const changePrice = (index) => {
  if (index) {//批量改价
    BatchVisible.value = true

  } else {//快速改价
    if (!newList.value.length) return proxy.$modal.msgWarning("请选择下架商品");
    FastVisible.value = true

  }
}
const handleBatchClose = () => {
  BatchVisible.value = false
  FastVisible.value = false
  skuVisible.value = false
}
const handleBatchSure = () => {
  BatchVisible.value = false
  productCheckList.value = []
  newList.value = []
  getList();
}
const handleImage = (row) => {
  var imageExtensionsRegex = /^https?:\/\//i;
  console.log(imageExtensionsRegex.test(row.mainImage));
  if (!imageExtensionsRegex.test(row.mainImage)) {
    return row.host
  } else {
    return row.mainImage
  }
}
const getBasics = () => {
  site.general
    .sitewebsiteGetbyid({
      pathParams: {
        id: Number(route.query.id),
      },
    })
    .then((res) => {
      //基础信息==》货币列表
      if (res.code === 200) {
        priceUnit.value = res.data.currency.description;
      }
    });
};
const handlePublicSure = () => {
  publicFrom.value = {};
  PublicDialog.value = false
}
const handlePublicClose = () => {
  publicFrom.value = {};
  PublicDialog.value = false
}
</script>